package cn.fly.blog.common.helper;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Log4j2
@Component
public class JsonHelper {

    public static ObjectMapper jacksonMapper;

    public static String toJson(Object o) {
        try {
            return jacksonMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String json, Class<T> klass) {
        try {
            return jacksonMapper.readValue(json, klass);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Autowired
    public void setJacksonMapper(ObjectMapper jacksonMapper) {
        JsonHelper.jacksonMapper = jacksonMapper;
    }
}
